﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Zxb.DayWork.Logic
{
    //依赖 EstateStat 表中的DayCaseListClicks，DayCaseInfoClicks历史数据
    //必须在ClickWorker执行之后执行，否则会造成某日点击量丢失
    //依赖sitestatus，但可反复执行
    //依赖数据库中存储过程EstateManageUpdateTotalClick, 表值类型UdtEstateManageUpdateTotalClick
    public class TotalClickWorker : BatchWorker
    {
        DateTime startDay;
        DateTime endDay;
        DataTable targetDT;
        bool quit = false;
        readonly string statusName = "EstateManage总点击量已更新最大日期";

        public TotalClickWorker(DateTime lastDay)
        {
            //EstateStat 中的Click数据只有前天的，所以不应该统计前天之后的
            DateTime haveDataDay = DateTime.Now.AddDays(-1.0);
            endDay = (lastDay > haveDataDay) ? haveDataDay : lastDay;
            if (!DateTime.TryParse(DAL.GetLastStatusValue(statusName), out startDay))
            {
                quit = true;
            }
        }

        public TotalClickWorker()
            : this(DateTime.Now)
        {

        }

        private static DataTable ReadDt_Estate_CaseListClicks(DateTime start, DateTime end)
        {
            string sql = string.Format("select RealEstateID,SUM(DayCaseListClicks) as CaseListClicks,SUM(DayCaseInfoClicks) as CaseInfoClicks from EstateStat where StatDate>='{0}' and StatDate<'{1}' group by RealEstateID ", start.ToString("yyyy-MM-dd 00:00"), end.ToString("yyyy-MM-dd 00:00"));
            return DAL.ReadDt_Retry_ReturnNewIfNull(DB.ZxbReader, sql);
        }

        protected override void ReadData()
        {
            if (quit)
            {
                return;
            }

            targetDT = ReadDt_Estate_CaseListClicks(startDay, endDay);
            if (targetDT.Rows.Count == 0)
            {
                quit = true;
                return;
            }
        }

        protected override void ProcessData()
        {

        }

        protected override void WriteData()
        {
            if (quit)
            {
                return;
            }

            bool flag = DAL.TVPUpdate(targetDT, "EstateManageUpdateTotalClick", "UdtEstateManageUpdateTotalClick");
            if (flag)
            {
                DAL.UpdateLastStatusValue(statusName, endDay.ToString("yyyy-MM-dd 00:00"));
            }
        }
    }
}
